package com.wj.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wj.domain.param.BookParam;
import com.wj.domain.vo.BookVO;
import com.wj.domain.vo.DiseasesInsectVO;
import com.wj.domain.vo.PlantTypeVO;
import com.wj.service.BookService;
import com.wj.tool.common.bean.restful.RestfulBody;
import com.wj.tool.common.utils.StringUtils;
import com.wj.tool.common.utils.paging.QueryParameters;
import com.wj.tool.common.utils.paging.QueryResults;
import com.wj.tool.utils.DbOperationUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RestfulBody
@Api(tags = "小说管理")
public class BookRestController {

    @Resource
    private BookService bookService;

    /**
     * 分页搜索
     */
    @PostMapping("/searchByPage")
    @ApiOperation("分页查询小说列表")
    public QueryResults<BookVO> searchByPage(@RequestBody QueryParameters<BookParam> parameters) {
        return bookService.getBookPage(parameters);
    }

    /**
     * 小说详情
     */
    @GetMapping("/detail")
    @ApiOperation("小说详情")
    public BookVO getBookInfo(@RequestParam("id") Long id) {
        return bookService.getBookById(id);
    }


    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        crawlData ();
    }

    public static void crawlData() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection(DbOperationUtils.jdbcUrl, DbOperationUtils.username, DbOperationUtils.password);
        Statement stat = connection.createStatement();
        String sql = "SELECT pt.id, pt.name FROM gh_plant_type pt";
        ResultSet rs = stat.executeQuery(sql);
        List<PlantTypeVO> plantTypeList = new ArrayList<>();
        while (rs.next()){
            PlantTypeVO plantTypeVO = new PlantTypeVO();
            plantTypeVO.setId(rs.getString("id"));
            plantTypeVO.setName(rs.getString("name"));
            plantTypeList.add(plantTypeVO);
        }
        if (CollUtil.isEmpty(plantTypeList)){
            return;
        }
        String s = HttpUtil.get("https://sinosaas.sino-eco.com/guan-tian/grow/diseasesCrop/index1");
        JSONObject jsonObject = JSON.parseObject(s);
        JSONArray resultArr = jsonObject.getJSONArray("result");
        List<DiseasesInsectVO> diseasesInsectList = new ArrayList<>();
        for (int i=0;i<resultArr.size();i++){
            JSONObject typeJson = resultArr.getJSONObject(i);
            JSONArray plantTypeArr = typeJson.getJSONArray("childrens");
            for (int j=0;j<plantTypeArr.size();j++){
                JSONObject plantTypeJson = plantTypeArr.getJSONObject(j);
                String name = plantTypeJson.getString("name");

                List<PlantTypeVO> collect = plantTypeList.stream().filter(plantTypeVO -> plantTypeVO.getName().equals(name)).collect(Collectors.toList());
                collect.forEach(plantTypeVO -> {
                    JSONArray hChildrens = plantTypeJson.getJSONArray("childrens");
                    for (int k=0;k<hChildrens.size();k++){
                        DiseasesInsectVO diseasesInsectVO = new DiseasesInsectVO();
                        JSONObject hJson = hChildrens.getJSONObject(k);
                        String hname = hJson.getString("name");
                        String type = hJson.getString("type");
                        if ("病害".equals(type)){
                            diseasesInsectVO.setType(1);
                        } else {
                            diseasesInsectVO.setType(2);
                        }
                        diseasesInsectVO.setPlantTypeName(name);
                        diseasesInsectVO.setName(hname);
                        diseasesInsectVO.setPlantTypeId(plantTypeVO.getId());
                        String code = hJson.getString("code");
                        diseasesInsectVO.setCode(code);
                        diseasesInsectList.add(diseasesInsectVO);
                    }

                });

            }
        }

        AtomicInteger i= new AtomicInteger();
        if (CollUtil.isNotEmpty(diseasesInsectList)){
            diseasesInsectList.forEach(diseasesInsectVO -> {
                int andIncrement = i.getAndIncrement();
                System.out.println("第"+andIncrement+"次："+diseasesInsectVO.getPlantTypeName());
                String code = diseasesInsectVO.getCode();
                String dataStr = HttpUtil.get("https://sinosaas.sino-eco.com/guan-tian/grow/diseasesCrop/getDataByCode?code="+code);
                JSONObject dataStrJson = JSON.parseObject(dataStr);
                JSONObject resultJson = dataStrJson.getJSONObject("result");
                JSONObject data = resultJson.getJSONObject("data");
                String prefix = resultJson.getString("prefix");
                String content = data.getString("content");
                if (StringUtils.isNotEmpty(content)){
                    Document contentDocument = Jsoup.parse(content);
                    // 症状
                    Element lblDamageSym = contentDocument.getElementById("lblDamageSym");
                    String lblDamageSymText = lblDamageSym.text();
                    diseasesInsectVO.setSymptom(lblDamageSymText);
                    // 原因
                    Element lblOFactor = contentDocument.getElementById("lblOFactor");
                    String lblOFactorText = lblOFactor.text();
                    diseasesInsectVO.setFeatureReason(lblOFactorText);
                    // 防治
                    Element lblCMethod = contentDocument.getElementById("lblCMethod");
                    String lblCMethodText = lblCMethod.text();
                    diseasesInsectVO.setControlMethods(lblCMethodText);
                }
                SnowflakeGenerator idGen = new SnowflakeGenerator();
                diseasesInsectVO.setId(idGen.next().toString());
                String imageUrls = data.getString("imageUrl");
                if (StringUtils.isNotEmpty(imageUrls)){
                    diseasesInsectVO.setImage(imageUrls);
                    String[] imgArr = imageUrls.split(",");
                    for (String img:imgArr){
                        String[] imgsplit = img.split("/");
                        File f = new File("D://"+imgsplit[0]);
                        if (!f.exists()){
                            f.mkdir();
                        }
                        File file = new File(f.getAbsolutePath() + "/" + imgsplit[1]);
                        if (!file.exists()){
                            file.mkdir();
                        }

                        //定义一个URL对象，就是你想下载的图片的URL地址
                        URL url = null;
                        try {
                            url = new URL(prefix+"/"+img);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                        //打开连接
                        HttpURLConnection conn = null;
                        try {
                            conn = (HttpURLConnection) url.openConnection();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //设置请求方式为"GET"
                        try {
                            conn.setRequestMethod("GET");
                        } catch (ProtocolException e) {
                            e.printStackTrace();
                        }
                        //超时响应时间为10秒
                        conn.setConnectTimeout(10 * 1000);
                        //通过输入流获取图片数据
                        InputStream is = null;
                        try {
                            is = conn.getInputStream();
                            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
                            byte[] bytes = readInputStream(is);
                            //创建一个文件对象用来保存图片，默认保存当前工程根目录，起名叫Copy.jpg
                            File imageFile = new File(file.getAbsolutePath()+"/"+imgsplit[2]);
                            if (imageFile.exists()){
                                continue;
                            }
                            //创建输出流
                            FileOutputStream outStream = new FileOutputStream(imageFile);
                            //写入数据
                            outStream.write(bytes);
                            //关闭输出流，释放资源
                            outStream.close();
                        } catch (Exception e) {
                            continue;
                        }

                    }
                }
            });
        }
        JdbcTemplate jdbcTemplate = DbOperationUtils.getJdbcTemplate();

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        if (CollUtil.isNotEmpty(diseasesInsectList)){
            jdbcTemplate.batchUpdate(" insert into gh_diseases_insect " + "(id,name,type,symptom," +
                    "control_methods,feature_reason,image,plant_type_id,deleted,create_time,update_time) " +
                    " values (?,?,?,?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setString(1, diseasesInsectList.get(i).getId());
                    ps.setString(2, diseasesInsectList.get(i).getName());
                    ps.setInt(3, diseasesInsectList.get(i).getType());
                    ps.setString(4, diseasesInsectList.get(i).getSymptom());
                    ps.setString(5, diseasesInsectList.get(i).getControlMethods());
                    ps.setString(6, diseasesInsectList.get(i).getFeatureReason());
                    ps.setString(7, diseasesInsectList.get(i).getImage());
                    ps.setString(8, diseasesInsectList.get(i).getPlantTypeId());
                    ps.setInt(9, 0);

                    ps.setTimestamp(10, timestamp);
                    ps.setTimestamp(11, timestamp);
                }

                @Override
                public int getBatchSize() {
                    return diseasesInsectList.size();
                }
            });
        }

    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

}